package org.example.initializer;

import org.example.constants.UserConstant;
import org.example.domain.User;
import org.example.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Component
public class BloomFilterInitializer implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void run(String... args) {
        // 创建用户布隆过滤器
        RBloomFilter<String> usernameBloomFilter = redissonClient.getBloomFilter(UserConstant.BLOOM_USER_USERNAME);
        // 在这里触发addToBloomFilter方法
        List<User> userList = userService.list();
        if(userList.size() > 0){
            usernameBloomFilter.tryInit(userList.size(), 0.01); // 1000表示预计的元素数量，0.01表示预计的误判率
            userList.forEach(e -> usernameBloomFilter.add(e.getUsername()));
        }

    }
}
